<template>
	<view class="content">
		<template v-if="hasLogin">
			<uni-list>
				<uni-list-item :title="username"></uni-list-item>
				<uni-list-item title="发布文章" to="/pages/publish/publish" :showArrow="true"></uni-list-item>
			</uni-list>
			<button type="default" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber">获取手机号</button>
		</template>
		<template v-else>
			<button type="default" open-type="getUserInfo" @getuserinfo="getUserInfo">微信登录</button>

			<navigator url="/pages/login/login">
				<button type="default">登录</button>
			</navigator>
		</template>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import WXBizDataCrypt from '@/wx_cryjs_sdk/WXBizDataCrypt.js';
	export default {
		data() {
			return {
				hasWeixinAuth: false,
				userInfo: null,
				encryptedData: null,
				iv: null,
			}
		},
		computed: {
			...mapState(['hasLogin', 'username', 'role'])
		},
		methods: {
			...mapMutations(['login']),
			decryptPhoneNumber(e) {
				if (e.detail.errMsg == "getPhoneNumber:fail user deny") { //用户决绝授权  
					return
					//拒绝授权后弹出一些提示  
				}
				this.encryptedData = e.detail.encryptedData //加密的用户信息
				this.iv = e.detail.iv //加密算法的初始向量  时要用到
				this.getWeixinCode().then((code) => {
					uniCloud.callFunction({
						name: 'user-center',
						data: {
							action: 'code2SessionWeixin',
							params: {
								code
							}
						},
						success: res => {
							let pc = new WXBizDataCrypt("wxed3265f73083507d", res.result.sessionKey); //wxXXXXXXX为你的小程序APPID
							let data = pc.decryptData(e.detail.encryptedData, e.detail.iv);
							// 初始化 本地信息
							// 更新云函数
							uniCloud.callFunction({
								name: 'user-center',
								data: {
									action: 'updateUser',
									params: {
										mobile: data.phoneNumber
									}
								},
								success: res => {
									console.log('updatePhone', res)
								},
								fail(e) {
									console.error(e)
									uni.showModal({
										showCancel: false,
										content: '请求云函数失败phone，请稍后再试'
									})
								}
							})
						},
						fail(e) {
							uni.showModal({
								showCancel: false,
								content: '请求云函数失败，请稍后再试'
							})

						}
					})

				})
			},
			getUserInfo(e) {
				if (!e.detail.userInfo) {
					uni.switchTab({
						url: '../index/index'
					})
					return uni.showToast({
						title: '登录失败，访问受限',
						icon: 'none'
					});
				}
				this.userInfo = e.detail.userInfo
				this.loginByWeixin()
			},
			updateUser(token, tokenExpired) {
				uniCloud.callFunction({
					name: 'user-center',
					data: {
						action: 'updateUser',
						params: this.userInfo
					},
					success: res => {
						console.log('updateuser', res)
						this.login({
							userinfo: this.userInfo,
							role: res.result.role || null,
							token: token,
							tokenExpired: tokenExpired
						})
					},
					fail(e) {
						console.error(e)
						uni.showModal({
							showCancel: false,
							content: '请求云函数失败，请稍后再试'
						})
					}
				})
			},
			getSessionKey() {

			},
			getWeixinCode() {
				return new Promise((resolve, reject) => {
					// #ifdef APP-PLUS
					weixinAuthService.authorize(function(res) {
						resolve(res.code)
					}, function(err) {
						console.log(err)
						reject(new Error('微信登录失败'))
					});
					// #endif
					// #ifdef MP-WEIXIN
					uni.login({
						provider: 'weixin',
						success: (res) => {
							resolve(res.code)
						},
						fail(err) {
							reject(new Error('微信登录失败'))
						}
					})
					// #endif
				})
			},
			loginByWeixin() {
				this.getWeixinCode().then((code) => {
					return uniCloud.callFunction({
						name: 'user-center',
						data: {
							action: 'loginByWeixin',
							params: {
								code,
							}
						}
					})
				}).then((res) => {
					console.log(JSON.stringify(res.result))
					if (res.result.code === 0) {
						let token = res.result.token
						let tokenExpired = res.result.tokenExpired
						this.updateUser(token, tokenExpired)
						uni.setStorageSync('uni_id_token', token)
						uni.setStorageSync('uni_id_token_expired', tokenExpired)
					}
				}).catch((e) => {
					console.error(e)
					uni.showModal({
						showCancel: false,
						content: '微信登录失败，请稍后再试'
					})
				})
			},
		}
	}
</script>

<style>

</style>
